<?php

namespace App\Http\Middleware;

use App\Models\NewMenu;
use App\Models\NewUsers;
//use Encore\Admin\Auth\Permission as Checker;
//use Encore\Admin\Facades\Admin;
//use Encore\Admin\Admin;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;

// 新权限中间件
class Permission
{
    use \App\Traits\Cache;
    /**
     * @var string
     */
//    protected $middlewarePrefix = 'admin.permission:';

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param array                    $args
     *
     * @return mixed
     */
    public function handle(Request $request, \Closure $next, ...$args)
    {

        $uri = getCurrentUri();

        if ($uri == 'admin') {
            $uri = '/';
        }

        // 未登录：无需验证的页面
        if (auth()->guest() && $this->shouldPassThrough($request)) {
            return $next($request);
        }

        // 已登录：无需验证的页面
        if ($this->loginShouldPassThrough($request)) {
            return $next($request);
        }

        $user= $request->user();
        if ($user->isAdministrator()) {
            \Log::info('是管理员---');
            return $next($request);
        }
        $input = $request->input();

        // 缓存 12小时
        $myMenuUri = Cache::remember(config('constants.User_menu_key_uri').$user->id, 60*60*12, function () use($user) {

            \Log::info('缓存过期');
            /*$roleId = $user->roles->pluck('id')->toArray();
            $table = config('admin.database.role_menu_table');
            $menuId = \DB::table($table)->whereIn('role_id', $roleId)->pluck('menu_id');*/
            $menuId = User::userPermisMenu($user);
            return  NewMenu::whereIn('id', $menuId)->whereNotNull('uri')->pluck('uri')->toArray();

        });

//        $myMenuUri[] = '/'; //首页
//        $myMenuUri[] = config('admin.auth.myInfo'); //用户中心
        $method = $request->method();

        // 资源类型路由：_method = ( create,edit,delete )
        $_method = @$input['_method'];

        if ( in_array($method, ['POST', 'PUT', 'DELETE']) ) {
//            $method == 'PUT' && $_method = $method;
            if ($_method =='delete') {
                if (@$input['_mode'] == 'batch_delete') {// 批量删除
                    $uri = $uri.'/'.$input['_mode'];
                } else {
                    $uri = $uri.'/'.$_method;
                }
            } elseif($_method =='PUT' || $method == 'PUT') {
                $uri = $uri.'/edit';

            } elseif(@$input['_mode'] == 'create') {
                $uri = $uri.'/create';

            } else {
                \Log::info('permission-其他');
                if ($uri2 = $this->hasAcUrl($request)) {
                    $uri = $uri2.$request->input('_mode');
                    $uri =  str_replace('/admin/','', $uri);

                } else {
                    \Log::info('权限配置有误');
                }
            }
        }


//        \Log::info($uri);
//        \Log::info($myMenuUri);
        self::cache('myPermissionMenuUri-'.$user->id, $myMenuUri);

        if (!in_array($uri, $myMenuUri) ) {

            if ($request->header('X-PJAX')) {
                \Log::info('Checker 无权访问');
                Checker::error();// 无权访问

            }
            elseif($request->input('_action')) {
                return response(['status'=> false, 'swal'=> [
                    'title'=> '无权操作2！',
                    'type'=> 'error'
                ]]);
            }
            else {
                return response(['message'=> '无权操作3！', 'status'=> false]);
            }
        }

        return $next($request);

    }


    // 返回正确的uri
    protected function hasAcUrl($request)
    {
        $_url = $request->input('_url') ;
        if ($_url )  {
            $action = strstr($_url, '/admin/');
            $arr = explode('/',$action);
            $mode = $request->input('_mode');
//            $key = $request->input('_key');
//            if ($key && !is_array($key)) {
            if (in_array($mode, ['edit','delete'])) {
//                $ac = rtrim($arr[count($arr)-1],'s');
                $ac = Str::singular($arr[count($arr)-1]); // 复数转单数

                return  $action.'/{'.$ac.'}/';
            } else {
                return  $action.'/';
            }

        }

        return false;

    }

   /* protected function previousPage(Request $req)
    {

        if ( $req->getMethod('Referer') != 'POST') {
            return false;
        }


        $referer = $req->header('Referer');
        \Log::info('上一个页面'.$referer);

//        $uri = str_replace('http://erp.martin.net/v2/','', $referer);
        $uri = strstr($referer,'/admin/');
        return str_replace('/admin/','', $uri);

    }*/



    /**
     * If the route of current request contains a middleware prefixed with 'admin.permission:',
     * then it has a manually set permission middleware, we need to handle it first.
     *
     * @param Request $request
     *
     * @return bool
     */
    public function checkRoutePermission(Request $request)
    {
        if (!$middleware = collect($request->route()->middleware())->first(function ($middleware) {
            return Str::startsWith($middleware, $this->middlewarePrefix);
        })) {
            return false;
        }

        $args = explode(',', str_replace($this->middlewarePrefix, '', $middleware));

        $method = array_shift($args);

        if (!method_exists(Checker::class, $method)) {
            throw new \InvalidArgumentException("Invalid permission method [$method].");
        }

        call_user_func_array([Checker::class, $method], [$args]);

        return true;
    }



    /**
     * Determine if the request has a URI that should pass through verification.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function shouldPassThrough($request)
    {
        // 游客不验证权限
        $excepts = array_merge(config('admin.auth.excepts', []), [
//            '_handle_action_',
//            '_handle_form_',
//            '_handle_selectable_',
//            '_handle_renderable_',
        ]);

        $a= collect($excepts)
            ->map('admin_base_path')
            ->contains(function ($except) use ($request) {
                if ($except !== '/') {
                    $except = trim($except, '/');
                }

                return $request->is($except);
            });

        \Log::info($a);
        return $a;
    }


    //
    protected function loginShouldPassThrough($request)
    {
        // 登录不验证权限
        $excepts = [
            '/',
            'auth/logs',
            'roles/menuTree',
            'roles/copy',
            'users/menu_tree',
            'users/roleupdate',
            'users/sale_accounts',
            'users/categories',
            'users/role_auth_list',
            'users/getstaffinfo',
            'auth/logout',
            'auth/setting',
        ];

        return collect($excepts)
            ->map('admin_base_path')
            ->contains(function ($except) use ($request) {
                if ($except !== '/') {
                    $except = trim($except, '/');
//                    \Log::info('已登录:'.$except);
                }

                return $request->is($except);
            });
    }
}
